import { _decorator, Button, Node, EventHandler } from 'cc';
import { BaseUI } from '../base/base-ui';
const { ccclass, property } = _decorator;

/**
 * 基础按钮组件
 * 所有按钮都应该继承此类
 */
@ccclass('BaseButton')
export class BaseButton extends BaseUI {
    /** 按钮组件 */
    protected button: Button | null = null;

    /** 是否启用点击音效 */
    @property
    protected enableClickSound: boolean = true;

    /** 点击音效名称 */
    @property
    protected clickSoundName: string = 'button-click';

    /** 是否启用点击动画 */
    @property
    protected enableClickAnimation: boolean = true;

    /** 点击缩放比例 */
    @property
    protected clickScale: number = 0.9;

    /** 点击动画时长（秒） */
    @property
    protected clickDuration: number = 0.1;

    /**
     * 生命周期：加载时
     */
    protected override onLoad(): void {
        super.onLoad();
        this.button = this.getComponent(Button);
        if (!this.button) {
            this.button = this.addComponent(Button);
        }
        this.componentName = 'BaseButton';
    }

    /**
     * 注册触摸事件
     */
    protected override registerTouchEvents(): void {
        super.registerTouchEvents();
        if (this.button) {
            // 添加点击事件
            const clickHandler = new EventHandler();
            clickHandler.target = this.node;
            clickHandler.component = 'BaseButton';
            clickHandler.handler = 'onClick';
            this.button.clickEvents.push(clickHandler);
        }
    }

    /**
     * 按钮点击回调
     * @param event 事件对象
     */
    protected onClick(): void {
        if (this.enableClickSound) {
            this.playClickSound();
        }
        if (this.enableClickAnimation) {
            this.playClickAnimation();
        }
    }

    /**
     * 播放点击音效
     */
    protected playClickSound(): void {
        // TODO: 实现音效播放
        this.logger.debug(`[${this.componentName}] Playing click sound: ${this.clickSoundName}`);
    }

    /**
     * 播放点击动画
     */
    protected playClickAnimation(): void {
        const node = this.node;
        const originalScale = node.scale;
        
        // 缩小动画
        node.setScale(originalScale.x * this.clickScale, originalScale.y * this.clickScale);
        
        // 恢复动画
        this.scheduleOnce(() => {
            node.setScale(originalScale);
        }, this.clickDuration);
    }

    /**
     * 设置按钮是否可交互
     * @param enabled 是否可交互
     */
    public setInteractable(enabled: boolean): void {
        if (this.button) {
            this.button.interactable = enabled;
        }
    }

    /**
     * 设置按钮是否启用
     * @param enabled 是否启用
     */
    public setEnabled(enabled: boolean): void {
        if (this.button) {
            this.button.enabled = enabled;
        }
    }
} 